package com.mathdroid.gui;

import java.awt.Toolkit;

import javax.swing.JFrame;

/**
 * The CenteredFrame aligns a JFrame to the center of the screen after pack()
 * is called.
 */
public abstract class CenteredFrame extends JFrame {
	/**
	 * Default UID.
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * Standard constructor. Creates frame without title.
	 */
	public CenteredFrame() {
		super();
	}
	
	/**
	 * Constructor.
	 * @param title The title.
	 */
	public CenteredFrame(final String title) {
		super(title);
	}

	/**
	 * Aligns the JFrame to the center of the screen. Should not be called 
	 * before pack() because dimensions would be unknown.
	 */
	private void center() {
		int screenWidth = 0;
		int screenHeight = 0;
		int frameWidth = 0;
		int frameHeight = 0;
		
		/* Get the dimensions of the Screen. */
		screenWidth = 
			(int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
		screenHeight =
			(int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
		
		/* Get the dimension of the JFrame after pack(). */
		frameWidth = this.getWidth();
		frameHeight = this.getHeight();
		
		this.setLocation(
				(screenWidth / 2) - (frameWidth / 2), 
				(screenHeight / 2) - (frameHeight / 2)
				);
	}
	
	/**
	 * Overwrites pack() to call center() afterwards.
	 */
	public final void pack() {
		super.pack();
		this.center();
	}
}
